import VueRouter from 'vue-router'
// 路由切换:组件是注册在挂载具体路由文件内的
import About from '../pages/About.vue'
import Home from '../pages/Home.vue'
import News from '../pages/News.vue'
import Message from '../pages/Message.vue'
import Detail from '../pages/Detail.vue'

const router = new VueRouter({
    // 易出错的配置变量名routers
    routes: [
        {
            name: 'guanyu',
            path: '/about',
            component: About,
            meta: {
                title: '关于'
            }
        },
        {
            name: 'jia',
            path: '/home',
            component: Home,
            meta: {
                title: '主页'
            },
            children: [
                {
                    name: 'xingwen',
                    path: 'news',
                    component: News,
                    meta: {
                        isAuth: true, title: '新闻'
                    }
                },
                {
                    name: 'xiaoxi',
                    path: 'message',
                    component: Message,
                    meta: {
                        isAuth: true, title: '消息'
                    },
                    children: [
                        {
                            name: 'xiangqin',
                            path: 'detail',
                            component: Detail,
                            meta: {
                                isAuth: true, title: '详情'
                            },
                            props($route) {
                                return { id: $route.query.id, title: $route.query.title }
                            }
                        }
                    ]
                }
            ]
        }
    ],


})
// 全局前置路由守卫--初始化的时候被调用,每次路由切换之前被调用
router.beforeEach((to, from, next) => {
    // 写法一:
    // if (to.name === 'xingwen' || to.name === 'xiaoxi') {
    //     if (localStorage.getItem('school') === 'bz') {
    //         next()
    //     }else {
    //         alert('学校名错误,无权限!')
    //     }
    // }else {
    //     next()
    // }
    // 写法二: 配置meta配置项 对象内自定义属性 自定义属性值为真 则表示该路由组件需要权限认证 写法比上面简单
    if (to.meta.isAuth) {
        if (localStorage.getItem('school') === 'bz') {
            // document.title = to.meta.title
            next()
        } else {
            alert('学校名错误,无权限!')
        }
    } else {
        // document.title = to.meta.title
        next()
    }
})
// 全局后置路由守卫--初始化的时候被调用,每次路由切换之后被调用 
// 注意:一定是切换成功后后置路由守卫才会被调用
router.afterEach((to, from) => {
    console.log('访问没有权限的路由,切换就会失败,我不会被调用,我要被调用了切换路由就成功了');
    document.title = to.meta.title

})

export default router